package com.idcf.boathouse.product.untils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
//@Component
public class JsonUtils {

    public static final ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static String toJSONString(Object o) {
        String result = null;
        try {
            result = mapper.writeValueAsString(o);
        } catch (JsonProcessingException ignored) {
        }
        return result;
    }

    public static <T> T parse(String jsonString, Class<T> clazz) {
        T t = null;
        if (StringUtils.isNotBlank(jsonString)) {
            try {
                byte[] bytes = jsonString.getBytes(StandardCharsets.UTF_8);
                t = mapper.readValue(bytes, clazz);
            } catch (IOException ignored) {
            }
        }
        return t;
    }

    public static <T> T parseByJavaType(String jsonString, Class<T> clazz, Class<?>... elementClasses) {
        T t = null;
        if (StringUtils.isNotBlank(jsonString)) {
            try {
                byte[] bytes = jsonString.getBytes(StandardCharsets.UTF_8);
                JavaType javaType = mapper.getTypeFactory().constructParametricType(clazz, elementClasses);
                t = mapper.readValue(bytes, javaType);
            } catch (IOException ignored) {
            }
        }
        return t;
    }

    public static <T> T parseByTypeReference(String jsonString, TypeReference<T> valueTypeRef) {
        T t = null;
        if (StringUtils.isNotBlank(jsonString)) {
            try {
                byte[] bytes = jsonString.getBytes(StandardCharsets.UTF_8);
                t = mapper.readValue(bytes, valueTypeRef);
            } catch (IOException ignored) {
            }
        }
        return t;
    }


    private JsonUtils() {
        throw new IllegalStateException("Utility class");
    }
}
